package com.gzsxy.esjy.service.core.sign.handler;


import com.alibaba.fastjson.JSON;
import com.gzsxy.esjy.bus.message.InnerProtocol;
import com.gzsxy.esjy.bus.message.MessageFactory;
import com.gzsxy.esjy.common.base.exception.impl.CustomAssert;
import com.gzsxy.esjy.feign.NettyFile.FileService;
import com.gzsxy.esjy.service.base.dto.request.UploadRequest;
import com.gzsxy.esjy.service.base.dto.response.DefaultResponse;
import com.gzsxy.esjy.service.core.sign.dao.ArraignSignMapper;
import com.gzsxy.esjy.service.core.sign.dto.SignWebsocketDto;
import com.gzsxy.esjy.service.core.sign.entity.ArraignSign;
import com.gzsxy.esjy.service.core.sign.entity.ResourcesIndex;
import com.gzsxy.esjy.service.core.sign.enums.SignStatus;
import com.gzsxy.esjy.sign.InnerSignCode;
import com.gzsxy.esjy.sign.SignConstant;
import com.gzsxy.esjy.sign.dto.InnerSignDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author zhangxiaolong
 * @date 2022/7/13 11:36
 */
@Slf4j
@Component(SignHandlerCmd.DOCUMENT)
public class DocumentSignHandler implements BaseSignHandler {

    @Autowired
    private ArraignSignMapper arraignSignDao;

    @Autowired
    private MessageFactory<InnerProtocol> messageFactory;



    private String requestIdSpit = ",";

    @Autowired
    private FileService fileService;

    @Autowired
    protected ApplicationContext applicationContext;

    /**
     * 签名成功
     * requestId 处理handler-签名用户类型-签名用户账号-业务ID
     *
     * @param innerSignDto 签名实体
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signSuccess(InnerSignDto innerSignDto) {
        String[] params = innerSignDto.getRequestId().split(requestIdSpit);
        String signUserType = params[1];
        String userAccount = params[2];
        String id = params[3];

        ArraignSign arraignSign = arraignSignDao.selectById(id);
        CustomAssert.notTrue(null != arraignSign, "文书记录不存在");


        //上传文件
        UploadRequest uploadDto = new UploadRequest();
        uploadDto.setExpired(0);
        uploadDto.setContent(innerSignDto.getSignPdfBase64());
        uploadDto.setFileType("pdf");
        DefaultResponse response = fileService.uploadJson(uploadDto);
        ResourcesIndex resourcesIndex = JSON.parseObject(JSON.toJSONString(response.getData()), ResourcesIndex.class);
        arraignSign.setLatestFile(resourcesIndex.getFileIndex());

//        String test = processTask.getTest();
//        JSONObject jsonObject = JSON.parseObject(test);
//        SignFlowUtil.setSignFileData(arraignSign, jsonObject.getString("step_code"));
        arraignSignDao.updateById(arraignSign);
//        try {
//            //更新待办内容
//            TodoItem todoItem = new TodoItem();
//            todoItem.setDataId(arraignSign.getId());
//            this.applicationContext.publishEvent(new TodoItemChangeEvent(todoItem));
//        } catch (Exception e) {
//            log.warn("signSuccess 更新待办内容出现异常,arraignSign.id：【{}】",arraignSign.getId(),e);
//        }
//
//        SignWebsocketDto signWebsocketDto = new SignWebsocketDto(SignStatus.SIGN_SUCCESS);
//        messageFactory.send("message-center", new InnerProtocol().strip(1).cmd("/sign/" + userAccount).body(signWebsocketDto));
    }

    /**
     * 取消签名
     *
     * @param innerSignDto   签名实体
     * @param isDeviceCancel 是否设备取消
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelSign(InnerSignDto innerSignDto, boolean isDeviceCancel) {
        String[] params = innerSignDto.getRequestId().split(requestIdSpit);
        String signUserType = params[1];
        String userAccount = params[2];
        String id = params[3];

        ArraignSign arraignSign = arraignSignDao.selectById(id);
        CustomAssert.notTrue(null != arraignSign, "文书记录不存在");

        //前端取消，不发送消息到前端
        if (!isDeviceCancel) {
            return;
        }

        SignWebsocketDto signWebsocketDto;
        if (InnerSignCode.FILE_DOWNLOAD_ERROR_CODE == innerSignDto.getCode()) {
            signWebsocketDto = new SignWebsocketDto(SignStatus.FILE_NOT_FOUND);
        } else if (InnerSignCode.BUSY_SIGN_CODE == innerSignDto.getCode()) {
            signWebsocketDto = new SignWebsocketDto(SignStatus.DEVICE_BUSY_CODE);
        } else if(InnerSignCode.DISCONNECT_ERROR_CODE  == innerSignDto.getCode()){
            signWebsocketDto = new SignWebsocketDto(SignStatus.DEVICE_DISCONNECT_CODE);
        } else {
            signWebsocketDto = new SignWebsocketDto(SignStatus.DEVICE_CANCEL_SIGN);
        }

        messageFactory.send("message-center", new InnerProtocol().strip(1).cmd("/sign/" + userAccount).body(signWebsocketDto));
    }

    /**
     * 签名确认
     *
     * @param innerSignDto 签名实体
     */
    @Override
    public void signAck(InnerSignDto innerSignDto) {

    }

    /**
     * 更新设备状态 通过message-center消息中心转发webstocket协议给前端
     * @param innerSignDto 签名实体
     */
    @Override
    public void deviceStatus(InnerSignDto innerSignDto) {
        String[] params = innerSignDto.getRequestId().split(requestIdSpit);
        String signUserType = params[1];
        String userAccount = params[2];
        String id = params[3];

        SignWebsocketDto signWebsocketDto;
        if (InnerSignCode.BUSY_SIGN_CODE == innerSignDto.getCode()) {
            signWebsocketDto = new SignWebsocketDto(SignStatus.DEVICE_BUSY_CODE);
        } else if (InnerSignCode.START_SIGN == innerSignDto.getCode()) {
            signWebsocketDto = new SignWebsocketDto(SignStatus.SIGN_INFO, innerSignDto.getMsg());
        } else {
            return;
        }
        messageFactory.send("message-center", new InnerProtocol().strip(1).cmd("/sign/" + userAccount).body(signWebsocketDto));
    }

    /**
     * 收到签名板超过设定时间的请求回复
     *
     * @param innerSignDto 签名实体
     */
    @Override
    public void signRequestTimeOut(InnerSignDto innerSignDto) {
        String[] params = innerSignDto.getRequestId().split(requestIdSpit);
        String signUserType = params[1];
        String userAccount = params[2];
        String id = params[3];

        if (SignConstant.SIGN_CMD.equals(innerSignDto.getCommand())) {
            SignWebsocketDto signWebsocketDto = new SignWebsocketDto(SignStatus.SIGN_TIMEOUT);
            messageFactory.send("message-center", new InnerProtocol().strip(1).cmd("/sign/" + userAccount).body(signWebsocketDto));
        }
    }
}
